package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"short-video-mgr/cache"
	"short-video-mgr/model"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	redis_key := "video_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	var video []model.Video
	if cacheData == "" {
		model.DB.Debug().Find(&video)
		jsonData, _ := json.Marshal(video)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &video)
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "展示成功",
		"data": video,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	redis_key := "video_Detail"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	var video model.Video
	if cacheData == "" {
		model.DB.Debug().Where("id=?", id).First(&video)
		jsonData, _ := json.Marshal(video)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &video)
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "展示成功",
		"data": video,
	})
	return
}

func Like(c *gin.Context) {
	Uid, _ := strconv.Atoi(c.PostForm("Uid"))
	Vid, _ := strconv.Atoi(c.PostForm("Vid"))
	data := model.VideoLike{
		Uid: Uid,
		Vid: Vid,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
